package me.android.library.common;

import android.app.Activity;
import android.app.Application;

import com.blankj.utilcode.util.Utils;
import com.google.common.collect.Lists;

import java.lang.ref.WeakReference;
import java.util.List;

import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import me.android.library.common.service.ConnectivityService;
import me.android.library.common.service.CrashLogService;
import me.android.library.common.service.ScreenPowerService;
import me.android.library.utils.android.AppUtil;
import me.android.library.utils.android.ContextUtil;
import mylab.base.foundation.lang.Disposable;


@Slf4j
public abstract class App extends Application implements Disposable {

    @Getter
    private static App instance;

    private final WeakReference<List<Activity>> activitiesRef = new WeakReference<>(Lists.newArrayList());


    // -------------------------------------------------------------------------------
    // App Start
    // -------------------------------------------------------------------------------

    @Override
    public void onCreate() {
        super.onCreate();
        log.info("App created:{}".getClass().getSimpleName());
        instance = this;
        Utils.init(this);
        ContextUtil.init(this);
        init();
        log.info("App inited:{}".getClass().getSimpleName());
    }

    protected void init() {
        CrashLogService.getInstance().init();
        ScreenPowerService.getInstance().init();
        ConnectivityService.getInstance().init();
    }

    @Override
    public void dispose() {
        clearActivityList();
    }

    public void exit() {
        dispose();
        System.exit(0);
    }

    public boolean isDebug() {
        return AppUtil.isDebug();
    }


    // -------------------------------------------------------------------------------
    // Activity 管理
    // -------------------------------------------------------------------------------

    public List<Activity> getActivities(){
        return activitiesRef.get();
    }

    public void addActivity(Activity activity) {
        getActivities().add(activity);
    }

    public void removeActivity(Activity activity) {
        getActivities().remove(activity);
    }

    protected void clearActivityList() {
        if (!getActivities().isEmpty()) {
            for (Activity atv : getActivities()) {
                atv.finish();
            }
        }
        getActivities().clear();
        activitiesRef.clear();
    }

}
